package com.example.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 过滤所有的资源地址
// 过滤html、jsp、servlet、css、js、jpg、mp3、mp4
@WebFilter("/*")
public class Filter0 extends HttpFilter {

    @Override
    public void doFilter(ServletRequest req,
                         ServletResponse res,
                         FilterChain chain)
            throws IOException, ServletException {
        System.out.println("正在经过测试过滤器");
        // 请求地址是什么？如果说是login.html，看是否已经登录了
        // 如果登录了，就让他直接去到success.html，如果没登录，就放行
        // 请求地址是什么？如果说是success.html，看是否已经登录了
        // 如果登录了，就直接放行，如果没登录，就让它回登录页
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        // 请求的地址
        String path = request.getServletPath();
        System.out.println(path);
        Object token = request.getSession().getAttribute("token");
        System.out.println(token);
        if ("/login.html".equals(path)) {
            if (token != null) {
                // 登录了
                response.sendRedirect("success.html");
            } else {
                chain.doFilter(req, res);
            }
            return;
        }
        if ("/success.html".equals(path)) {
            if (token != null) {
                // 登录了
                chain.doFilter(req, res);
            } else {
                response.sendRedirect("login.html");
            }
            return;
        }
        chain.doFilter(req, res);
    }
}
